<?php


namespace app\common\cachemodel\lucky;


use app\common\cachemodel\UserCoupon;
use app\common\cachemodel\ZlCouponAttr;
use app\common\lib\exception\ApiException;
use app\common\lib\SensorsData;
use app\common\model\BaseCache;
use app\common\model\Goods;
use think\Cache;
use think\Db;
use think\Log;

class AppUserOldLuckyRecycle extends BaseCache
{
    protected $table = 'wechat_backup_07_18_14_43_00.app_user_old_lucky_recycle';

    /**
     * 确定 回收
     * @param $uid
     * @return bool
     */
    public function confirmRecycle($uid)
    {
        return (new AppUserLuckyInfo())->SaveData($uid);
    }


    /**
     * 获取销毁补偿信息结果 字符串
     * @param int $uid
     * @return string
     * @throws ApiException
     */
    public function getUserRecycleInfo(int $uid)
    {
        try
        {
            $resData = $this->where('uid', $uid)->find();

            $compensate = '';
            if ($resData)
            {   // 已经 回收销毁旧的幸运星了
                $compensate = $resData['compensate'];
            } else
            {   // 开始销毁
                $isRecycle = Cache::get('app_user_old_lucky_recycle:' . $uid, false);
                if ($isRecycle !== false)
                {
                    throw new ApiException('操作频繁，旧幸运星已经进行销毁了');
                }
                // 获取幸运星数量
                $luckyNum = Db::table('wechat_backup_07_18_14_43_00.app_user_lucky_num')->where('uid', $uid)->count();
                if ($luckyNum > 0)
                {
                    Cache::set('app_user_old_lucky_recycle:' . $uid, 1, 300);
                    switch (true)
                    {
                        case $luckyNum >= 2000:
                            $cids = [   // VIP 免费券 + 月运免费券
                                480 => 1,
                                481 => 1
                            ];
                            break;
                        case $luckyNum >= 1000 && $luckyNum < 2000:
                            $cids = [   // VIP 免费券
                                480 => 1,
                            ];
                            break;
                        case $luckyNum >= 500 && $luckyNum < 1000:
                            $cids = [   // 年运 5 折券
                                482 => 1
                            ];
                            break;
                        case $luckyNum >= 100 && $luckyNum < 500:
                            $cids = [   // VIP 5折券
                                483 => 1
                            ];
                            break;
                        default:    // 年运 + 月运 8折券
                            $cids = [
                                484 => 1,
                                485 => 1
                            ];
                    }
                    $userCouponModel = new UserCoupon();
                    $ids = [];
                    $nowTime = time();
                    foreach ($cids as $cid => $sendNum)
                    {
                        $couponInfo = (new ZlCouponAttr())->getInfoById($cid, ['desc', 'type', 'rand_min', 'rand_max', 'ur_id', 'gids']);
                        // 神策打点
                        $gidsArr = explode(',', $couponInfo['gids']);
                        $couponRangeArr = (new Goods())->where('id', 'in', $gidsArr)->column('name');
                        for ($i = 0; $i < $sendNum; $i++)
                        {
                            $cData = [
                                'uid' => $uid,
                                'c_id' => $cid,
                                'ur_id' => $couponInfo['ur_id'],
                                'start_time' => $nowTime,
                                'end_time' => strtotime("+30 day"),
                                'give_time' => $nowTime,
                                'status' => 0,
                                'price' => $couponInfo['type'] == 4 ? mt_rand($couponInfo['rand_min'], $couponInfo['rand_max']) : 0,
                                'is_give' => 0,
                                'create_time' => $nowTime,
                                'update_time' => 0,
                            ];
                            $ucId = $userCouponModel->insertGetId($cData);
                            $ids[$ucId] = $ucId; // 添加未用于ID
                            // 神策打点 75 获得优惠券 AcquireCoupon
                            SensorsData::track($uid, true, 'AcquireCoupon', [
                                'refer_name' => '',
                                'refer_link' => '',
                                'coupon_name' => $couponInfo['desc'],
                                'coupon_expire' => date('Y-m-d H:i:s', $cData['end_time']),
                                'coupon_type' => $userCouponModel->couponTypeName[$couponInfo['type']],
                                'coupon_range' => $couponRangeArr,
                                'acquire_channel' => "幸运星销毁",    //  打点
                                'is_give' => false,
                                'acquire_scene' => '系统赠送',
                            ]);
                        }
                        $compensate .= "{$couponInfo['desc']}{$sendNum}张、";
                    }
                    if ($ids)
                    {
                        // 未使用
                        $userCouponModel->listDataAdd($uid, $ids, 1);
                    }
                    $compensate = rtrim($compensate, '、');
                    $insertData = [
                        'uid' => $uid,
                        'num' => $luckyNum,
                        'compensate' => $compensate,
                        'create_time' => $nowTime
                    ];

                    $this->save($insertData);

                    // 神策打点 209 幸运星-销毁 LuckyStarDestory
                    SensorsData::track($uid, true, 'LuckyStarDestory', [
                        'destory_scene' => '旧幸运星销毁',   // 销毁场景 过期销毁、旧幸运星销毁
                        'destory_num' => $luckyNum,      //销毁数量
                    ]);
                }
            }
        }
        catch (\Exception $e)
        {
            Log::write('旧幸运星销毁 AppUserOldLuckyRecycle model 异常：' . $e->getMessage() . '失败行数：' . $e->getLine(), 'error');
            throw new ApiException('服务异常，请稍后再试～');
        }
        return $compensate;
    }
}
